#include "netTcpServer.h"


#include <QDebug>


/* 弹窗 */
#include <QMessageBox>


NetTcpServer::NetTcpServer(QObject *parent) : QObject(parent)
{
    /* 创建QTcpServer对象 */
    m_server = new QTcpServer(this);


    /* 信号和槽 - 绑定 */
    connect(m_server, &QTcpServer::newConnection, this, &NetTcpServer::handleNewConnectSlot);
}

/* 指定端口启动服务器 */
void NetTcpServer::startServer(uint16_t port)
{
    /* 绑定端口 */
    bool res = m_server->listen(QHostAddress::Any, port);
    if (res == false)
    {
        QMessageBox::warning(nullptr, "服务器启动", "启动失败");
        return;
    }
    qDebug() << "服务器启动成功" << endl;
}


/* 处理新的连接 */
void NetTcpServer::handleNewConnectSlot()
{
    qDebug() << "new connect coming...";

    /* 新的客户端 */
    QTcpSocket * clientSock = m_server->nextPendingConnection();

    /* 维护客户端信息 */
    m_clients.push_back(clientSock);

    /* 信号和槽的绑定 */
    connect(clientSock, &QTcpSocket::readyRead, this, &NetTcpServer::handleReadDataSlot);
}


/* 处理信息 - 槽函数 */
void NetTcpServer::handleReadDataSlot()
{
    /* 强制类型转换 */
    QTcpSocket * clientSock = qobject_cast<QTcpSocket *>(sender());

    /* 读取缓冲区的数据 */
    QByteArray data = clientSock->readAll();

    qDebug() << "data:" << data << endl;
}






